package services

import (
	"fmt"
	"zatta-gateway/pkg/db"
	dbModel "zatta-gateway/pkg/db/model"
	"zatta-gateway/pkg/model"
)

func ListModels(clientManager *db.ClientManager, modelID ...string) ([]*model.Model, error) {
	var err error
	var modelsToReturn []*model.Model
	var modelIDsFromDB []string
	var modelInfos []*dbModel.ModelInfo
	var rpcServers []*dbModel.RpcServer

	if len(modelID) > 1 {
		return nil, fmt.Errorf("only one modelID or no modelID is supported")
	}
	if len(modelID) == 1 {
		modelInfos, err = dbModel.ListModelInfoByName(clientManager.GetModelDB(), modelID[0])
		if err != nil {
			return nil, err
		}
	}
	modelInfos, err = dbModel.ListModelInfos(clientManager.GetModelDB())
	if err != nil {
		return nil, err
	}
	for _, modelInfo := range modelInfos {
		modelIDsFromDB = append(modelIDsFromDB, modelInfo.Name)
	}

	for _, id := range modelIDsFromDB {
		rpcServers, err = clientManager.GetRpcServersByModelName(id)
		if err != nil {
			return nil, err
		}

		var serverAddr []string
		for _, rpcServer := range rpcServers {
			serverAddr = append(serverAddr, rpcServer.ServiceAddr)
		}
		modelsToReturn = append(modelsToReturn, &model.Model{
			ID:         id,
			ClientAddr: serverAddr,
		})
	}
	return modelsToReturn, nil
}

func CheckIfModelExists(modelID string, clientManager *db.ClientManager) (bool, error) {
	if modelID == "" {
		return false, fmt.Errorf("modelID is empty")
	}
	models, err := ListModels(clientManager, modelID)
	if err != nil {
		return false, err
	}
	return len(models) > 0, nil
}
